package com.nanhu.sms;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import com.nanhu.sms.adapter.CheckBoxCursorAdapter;
import com.nanhu.sms.adapter.CheckBoxCursorAdapter.Selection;
import com.nanhu.sms.broadcast.SmsSendReceiver;
import com.nanhu.sms.widget.DashlineEditTextOne;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.telephony.SmsManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class SmsSendActivity extends FragmentActivity{
	
	private static final String[] PHONES_PROJECTION = new String[]{
		Phone._ID, Phone.DISPLAY_NAME, Phone.NUMBER, Phone.PHOTO_ID, Phone.CONTACT_ID
	};
	
	// 这是我们想获取的联系人中一行的数据．  
    static final String[] CONTACTS_SUMMARY_PROJECTION = new String[] {
        Contacts._ID,  
        Contacts.DISPLAY_NAME,  
        Contacts.CONTACT_STATUS,  
        Contacts.CONTACT_PRESENCE,  
        Contacts.PHOTO_ID,  
        Contacts.LOOKUP_KEY,  
    };  
	
	/**联系人显示名称**/  
    private static final int PHONES_DISPLAY_NAME_INDEX = 0;
    
    /**电话号码**/  
    private static final int PHONES_NUMBER_INDEX = 1;
    
    /**头像ID**/  
    private static final int PHONES_PHOTO_ID_INDEX = 2;
    
    /**联系人的ID**/  
    private static final int PHONES_CONTACT_ID_INDEX = 3;
    
    /**联系人名称**/  
    private static ArrayList<String> mContactsName = new ArrayList<String>();
    
    /**联系人头像**/  
    private static ArrayList<String> mContactsNumber = new ArrayList<String>();
    
    /**联系人头像**/  
    private static ArrayList<Bitmap> mContactsPhonto = new ArrayList<Bitmap>();
	
	private DashlineEditTextOne contentEditText;
	
	private static DialogFragment newFragment;
	
	private EditText receiver;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sms_send_layout);
		contentEditText = (DashlineEditTextOne)findViewById(R.id.content);
		receiver = (EditText)findViewById(R.id.receiver);
	}
	
	private void getPhoneContacts(){
		ContentResolver resolver = getContentResolver();
		Cursor phoneCursor = resolver.query(Phone.CONTENT_URI, PHONES_PROJECTION, null, null, null);
		if(phoneCursor != null){
			while(phoneCursor.moveToNext()){
				String phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX);
				String contactName = phoneCursor.getString(PHONES_DISPLAY_NAME_INDEX);
				Long contactId = phoneCursor.getLong(PHONES_CONTACT_ID_INDEX);
				Long photoId = phoneCursor.getLong(PHONES_PHOTO_ID_INDEX);
				
				Bitmap contactPhoto = null;
				if(photoId > 0){
					Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
					InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(resolver, uri);
					contactPhoto = BitmapFactory.decodeStream(input);
				}else{
					contactPhoto = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
				}
				
				mContactsName.add(contactName);
				mContactsNumber.add(phoneNumber);
				mContactsPhonto.add(contactPhoto);
			}
			
			phoneCursor.close();
		}
	}
	
	public void doSend(View view){
		ArrayList<Selection> receivers = (ArrayList<Selection>)receiver.getTag();
		String smsContent = contentEditText.getText().toString();
		
		if(TextUtils.isEmpty(smsContent)){
			AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
			alertBuilder.setMessage("请选择收信人");
			alertBuilder.setPositiveButton("确定", null);
			alertBuilder.show();
			return;
		}
		
		SmsManager sms = SmsManager.getDefault();
		List<String> texts = sms.divideMessage(smsContent);
		
		PendingIntent mPI = PendingIntent.getBroadcast(this, 0, produceIntent(receivers, smsContent), 0);
		
		for(Selection s : receivers){
			String phoneNumber = s.number;
			for(String text : texts){
				sms.sendTextMessage(phoneNumber, null, text, mPI, null);
			}
		}
		finish();
	}

	private Intent produceIntent(ArrayList<Selection> receivers, String smsContent) {
		Intent intent = new Intent(SmsSendReceiver.action);
		List<String> receiverList = new ArrayList<String>();
		for(Selection s : receivers){
			receiverList.add(s.number);
		}
		String[] receiverArray = new String[receiverList.size()];
		receiverList.toArray(receiverArray);
		intent.putExtra("receivers", receiverArray);
		intent.putExtra("content", smsContent);
		return intent;
	}
	
	public void selectReceiver(View view){
		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
		Fragment prev = getSupportFragmentManager().findFragmentByTag("receiverDialog");
		if(prev != null){
			return;
		}
		
		newFragment = new MyDialogFragment();
		newFragment.show(ft, "receiverDialog");
	}
	
	public class MyDialogFragment extends DialogFragment implements LoaderManager.LoaderCallbacks<Cursor>{
		
		//private ReceiversAdapter adapter;
		
		public CheckBoxCursorAdapter mAdapter;
		
		private ListView listView; 
		
		private LinearLayout progressBarContainer;
		
//		static MyDialogFragment newInstance(){
//			MyDialogFragment f = new MyDialogFragment();
//			return f;
//		}
		
		
		
		@Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			int style = DialogFragment.STYLE_NORMAL, theme = android.R.style.Theme;
			setStyle(style, theme);
			
			mContactsName.clear();
			mContactsNumber.clear();
			mContactsPhonto.clear();
			
			//adapter = new ReceiversAdapter();
			
			//getLoaderManager().initLoader(0, null, this);
		}
		
//		@Override 
//	    public Dialog onCreateDialog(Bundle savedInstanceState) { 
//	        String title = "title";
//	        return new AlertDialog.Builder(getActivity()) 
//	        .setIcon(R.drawable.ic_launcher) 
//	        .setTitle(title) 
//	        .setPositiveButton("OK", 
//	                new DialogInterface.OnClickListener() { 
//	            public void onClick(DialogInterface dialog,  
//	                    int whichButton) { 
//	                 
//	            } 
//	        }) 
//	        .setNegativeButton("Cancel", 
//	                new DialogInterface.OnClickListener() { 
//	            public void onClick(DialogInterface dialog,  
//	                    int whichButton) { 
//	                
//	            } 
//	        }).create(); 
//	    }         
	 
		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View v = inflater.inflate(R.layout.receiver_layout, container, false);
			listView = (ListView)v.findViewById(R.id.receivers);
			progressBarContainer = (LinearLayout)v.findViewById(R.id.progressBarContainer);
			progressBarContainer.setVisibility(View.VISIBLE);
			
			String receivers = receiver.getText().toString();
			ArrayList<Selection> selected = (ArrayList<Selection>)receiver.getTag();
			//selected.add("135719215");
			// 创建一个空的adapter，我们将用它显示加载后的数据  
	        mAdapter = new CheckBoxCursorAdapter(getActivity(),  
	                R.layout.colorlist, null,  
	                new String[] {Phone.DISPLAY_NAME, Phone.NUMBER },  
	                new int[] {R.id.title, R.id.text }, selected);
	        
	        listView.setAdapter(mAdapter);
	        getLoaderManager().initLoader(0, null, this);
	        
	        listView.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					CheckBox checkBox = (CheckBox)view.findViewById(R.id.checkBox);
					checkBox.setChecked(!checkBox.isChecked());
					mAdapter.onCheckChange(checkBox);
				}
			});
	        
			Button button = (Button)v.findViewById(R.id.doSelect);
			button.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					ArrayList<Selection> selected = mAdapter.getSelectedItems();
					StringBuffer names = new StringBuffer();
					int count = 0;
					for(Selection item : selected){
						if(item.number.trim().equals(""))
							continue;
						if(count > 0)
							names.append(",");
						names.append(item.name);
						count++;
					}
					receiver.setText(names.toString());
					receiver.setTag(selected);
					newFragment.dismiss();
				}
			});
			//listView.setAdapter(adapter);
			return v;
		}
		
		public void doSelect(View view){
			newFragment.dismiss();
		}
		
		@Override
		public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
			Uri baseUri = Phone.CONTENT_URI;
			String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("  
	                + Contacts.HAS_PHONE_NUMBER + "=1) AND ("  
	                + Contacts.DISPLAY_NAME + " != '' ))";
			
			return new CursorLoader(getActivity(), baseUri,  
					PHONES_PROJECTION, "", null,  
	                Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
		}

		@Override
		public void onLoadFinished(Loader<Cursor> loader, Cursor phoneCursor) {
			mAdapter.swapCursor(phoneCursor);
			progressBarContainer.setVisibility(View.GONE);
		}

		@Override
		public void onLoaderReset(Loader<Cursor> loader) {
			mAdapter.swapCursor(null);
		}
	}
	
	class SendReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			int resultCode = getResultCode();
			if(resultCode == Activity.RESULT_OK){
				Toast.makeText(SmsSendActivity.this, "发送成功！", Toast.LENGTH_SHORT).show();
			}else{
				Toast.makeText(SmsSendActivity.this, "发送失败！", Toast.LENGTH_SHORT).show();
			}
			
		}
		
	}
}
